<?php


namespace app\api\controller;


use app\common\controller\Api;
use think\Db;


//用户ID，快递鸟提供，注意保管，不要泄漏
defined('EBusinessID') or define('EBusinessID', '1775644');//即用户ID，登录快递鸟官网会员中心获取 https://www.kdniao.com/UserCenter/v4/UserHome.aspx
//API key，快递鸟提供，注意保管，不要泄漏
defined('ApiKey') or define('ApiKey', '3b917d76-0874-40d1-8e49-2af5d6f803d7');//即API key，登录快递鸟官网会员中心获取 https://www.kdniao.com/UserCenter/v4/UserHome.aspx
//请求url，正式地址
defined('ReqURL') or define('ReqURL', 'https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx');
session_start();

class Order extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取商品类别及产品数据
     */
    public function getProduct(){
        //产品信息
        $product = Db::name('product_category')->alias('a')
            ->join('product b','a.id = b.category_id')
            ->where(['a.status'=>1,'b.status'=>1])
            ->field('a.*,b.*,a.name as category_name')
            ->order('a.weight ASC')
            ->select();

        $nProduct = [];
        foreach ($product as $pk => $pv){
            if (!isset($nProduct[$pv['category_id']])){
                $nProduct[$pv['category_id']] = [];
            }
            $nProduct[$pv['category_id']][] = $pv;
        }

        //类别信息
        $category = Db::name('product_category')
            ->where(['status'=>1])
            ->order('weight ASC')
            ->column('name','id');

        $res['product'] = $nProduct;
        $res['category'] = $category;
        $this->success('',$res);
    }

    /**
     * 快递公司编码接口
     */
    public function getshippercode(){
        $this->success('',[
            'STO'=>'申通快递',
            'YTO'=>'圆通快递',
//            'ZTO'=>'中通快递',
//            'YD' =>'韵达快递',
//            'SF' =>'顺丰快递',
//            'JD' =>'京东快递',
//            'DBL'=>'德邦快递',
//            'EMS'=>'EMS'
            'HTKY'=>'百世快递',
            'JTSD'=>'极兔速递'
        ]);
    }

    /**
     * 根据运单号请求快递信息
     * @param  string $ShipperCode 快递公司编码
     * @param  string $LogisticCode 运单号
     */
    function getordertracesbyjson(){
        $param = $this->request->post();
        $ShipperCode = isset($param['ShipperCode'])?$param['ShipperCode']:'';
        $LogisticCode = isset($param['LogisticCode'])?$param['LogisticCode']:'';
        if (!$ShipperCode || !$LogisticCode){
            $this->error('参数不能为空！');
        }
        $SESSIONKEY = $ShipperCode.'-'.$LogisticCode;

        if(isset($_SESSION[$SESSIONKEY]))
        {
            $this->success('请求成功',json_decode($_SESSION[$SESSIONKEY],true));
        }
        // 组装应用级参数
        $requestData= "{".
            "'CustomerName': '',".
            "'OrderCode': '',".
            "'ShipperCode': '".$ShipperCode."',".
            "'LogisticCode': '".$LogisticCode."',".
            "}";
        // 组装系统级参数
        $datas = array(
            'EBusinessID' => EBusinessID,
            'RequestType' => '1002', //免费即时查询接口指令1002/在途监控即时查询接口指令8001/地图版即时查询接口指令8003
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, ApiKey);
        //以form表单形式提交post请求，post请求体中包含了应用级参数和系统级参数
        $result=$this->sendPost(ReqURL, $datas);

        //根据公司业务处理返回的信息......

        $result = json_decode($result,true);
        array_multisort(array_column($result['Traces'], 'AcceptTime'),SORT_DESC,$result['Traces']);
        $_SESSION[$SESSIONKEY] = json_encode($result);
        $this->success('请求成功',$result);
    }

    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    function sendPost($url, $datas) {
        $postdata = http_build_query($datas);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param ApiKey ApiKey
     * @return DataSign签名
     */
    function encrypt($data, $ApiKey) {
        return urlencode(base64_encode(md5($data.$ApiKey)));
    }



}